#include <iostream>
#include <fstream>
#include <sstream>
#include <utils/config.h>

namespace utils {
const std::string configFile = "config.cfg";

config::config(const std::string& currentPath) : appDir(currentPath/std::filesystem::path("Lorepona")) {
	if(not std::filesystem::exists(appDir))
		std::filesystem::create_directory(appDir);
    std::filesystem::path confFile = appDir/configFile;
    if(std::fstream file(confFile, std::ios::in | std::ios::out); file.is_open()) {
        std::string dataFromFile;
        std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(dataFromFile));
        std::istringstream iss(dataFromFile);
        std::string line;
        std::vector<std::string> tempLine = {};
        while (std::getline(iss, line)) {
            tempLine.push_back(line);
        }
        usersFile = tempLine[0];
        pathToUsersSecrets = tempLine[1];
    } else {
        std::ofstream file1;
        file1.open(confFile);
        file1 << appDir.string() + "/users.cfg\n";
        usersFile = appDir/ "users.cfg";
        std::filesystem::create_directory(appDir/"secrets");
        file1 << appDir.string() + "/secrets/";
        pathToUsersSecrets = appDir / "secrets/";
    }
}

void config::saveConfig() {
    std::filesystem::path confFile = appDir/configFile;
    std::fstream file(confFile, std::ios::in | std::ios::out);
    file << usersFile << "\n";
    file << pathToUsersSecrets << "\n";
}
}


